#include "prescriptionviewwidget.h"
#include "ui_prescriptionviewwidget.h"
#include "../../network/networkclient.h"
#include "prescriptiondetailwidget.h"
#include "chatwindow.h"
#include <QJsonArray>
#include <QPushButton>
#include <QHBoxLayout>

PrescriptionViewWidget::PrescriptionViewWidget(const Patient& patient, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PrescriptionViewWidget),
    m_patient(patient) {
    ui->setupUi(this);
    
    ui->prescriptionTable->setColumnCount(9);
    ui->prescriptionTable->setHorizontalHeaderLabels(
        {"处方ID", "开方时间", "药品", "剂量", "用法", "频次", "天数", "操作", "联系医生"});
    ui->prescriptionTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->prescriptionTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    
    // 设置列宽模式
    ui->prescriptionTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    ui->prescriptionTable->setColumnWidth(0, 80);
    ui->prescriptionTable->verticalHeader()->setDefaultSectionSize(40);
    ui->prescriptionTable->setColumnWidth(1, 150);
    ui->prescriptionTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); // 药品自动拉伸
    ui->prescriptionTable->setColumnWidth(3, 100);
    ui->prescriptionTable->setColumnWidth(4, 120); // 操作列加宽
    ui->prescriptionTable->setColumnWidth(5, 100);
    ui->prescriptionTable->setColumnWidth(6, 80);
    
    // 隐藏行号列避免乱码
    ui->prescriptionTable->verticalHeader()->setVisible(false);
    ui->prescriptionTable->setColumnWidth(7, 100); // 操作列
    
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &PrescriptionViewWidget::onMessageReceived);
    
    loadPrescriptions();
}

PrescriptionViewWidget::~PrescriptionViewWidget() {
    delete ui;
}

void PrescriptionViewWidget::on_refreshButton_clicked() {
    loadPrescriptions();
}

void PrescriptionViewWidget::loadPrescriptions() {
    QJsonObject request;
    request["patientId"] = m_patient.id;
    NetworkClient::instance().sendRequest(MSG_GET_PRESCRIPTIONS, request);
}

void PrescriptionViewWidget::onMessageReceived(MessageType type, const QJsonObject& data) {
    if (type == MSG_GET_PRESCRIPTIONS_RESPONSE) {
        if (data["success"].toBool()) {
            updatePrescriptionTable(data["prescriptions"].toArray());
        }
    }
}

void PrescriptionViewWidget::updatePrescriptionTable(const QJsonArray& prescriptions) {
    ui->prescriptionTable->setRowCount(0);
    m_prescriptions = prescriptions; // 存储处方数据
    
    for (const QJsonValue& value : prescriptions) {
        QJsonObject prescription = value.toObject();
        
        int row = ui->prescriptionTable->rowCount();
        ui->prescriptionTable->insertRow(row);
        
        ui->prescriptionTable->setItem(row, 0, 
            new QTableWidgetItem(QString::number(prescription["id"].toInt())));
        ui->prescriptionTable->setItem(row, 1, 
            new QTableWidgetItem(prescription["prescription_time"].toString()));
        ui->prescriptionTable->setItem(row, 2, 
            new QTableWidgetItem(prescription["medications"].toString()));
        ui->prescriptionTable->setItem(row, 3, 
            new QTableWidgetItem(prescription["dosage"].toString()));
        ui->prescriptionTable->setItem(row, 4, 
            new QTableWidgetItem(prescription["usage"].toString()));
        ui->prescriptionTable->setItem(row, 5, 
            new QTableWidgetItem(prescription["frequency"].toString()));
        ui->prescriptionTable->setItem(row, 6, 
            new QTableWidgetItem(QString::number(prescription["days"].toInt())));
        
        // 第7列：操作（查看详情）
        QPushButton* viewBtn = new QPushButton("查看详情");
        viewBtn->setMinimumHeight(30);
        viewBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        viewBtn->setProperty("row", row);
        connect(viewBtn, &QPushButton::clicked, this, &PrescriptionViewWidget::onViewDetailClicked);
        ui->prescriptionTable->setCellWidget(row, 7, viewBtn);
        
        // 第8列：联系医生（独立列）
        int doctorId = prescription["doctor_id"].toInt();
        QString doctorName = prescription["doctor_name"].toString();
        
        QPushButton* chatBtn = new QPushButton("联系医生");
        chatBtn->setMinimumHeight(30);
        chatBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        chatBtn->setProperty("doctorId", doctorId);
        chatBtn->setProperty("doctorName", doctorName);
        chatBtn->setStyleSheet(
            "QPushButton { background-color: #07C160; color: white; border-radius: 3px; }"
            "QPushButton:hover { background-color: #06AD56; }");
        connect(chatBtn, &QPushButton::clicked, this, &PrescriptionViewWidget::onChatWithDoctorClicked);
        ui->prescriptionTable->setCellWidget(row, 8, chatBtn);
    }
}

void PrescriptionViewWidget::onViewDetailClicked() {
    QPushButton* btn = qobject_cast<QPushButton*>(sender());
    if (!btn) return;
    
    int row = btn->property("row").toInt();
    
    if (row >= 0 && row < m_prescriptions.size()) {
        // 将JSON转换为Prescription对象
        QJsonObject prescriptionObj = m_prescriptions[row].toObject();
        Prescription prescription = Prescription::fromJson(prescriptionObj);
        
        // 打开处方详细窗口
        PrescriptionDetailWidget *detailWidget = new PrescriptionDetailWidget(prescription, nullptr);
        detailWidget->setWindowModality(Qt::ApplicationModal);
        detailWidget->show();
    }
}

void PrescriptionViewWidget::onChatWithDoctorClicked() {
    QPushButton* btn = qobject_cast<QPushButton*>(sender());
    if (!btn) return;
    
    int doctorId = btn->property("doctorId").toInt();
    QString doctorName = btn->property("doctorName").toString();
    
    // 打开聊天窗口
    ChatWindow* chatWindow = new ChatWindow(m_patient.id, doctorId, doctorName, "医生", this);
    chatWindow->setWindowModality(Qt::ApplicationModal);
    chatWindow->show();
}

